﻿using Spire.Barcode;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Presentation;
using Spire.Presentation.Drawing;
using Spire.Xls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Section = Spire.Doc.Section;

namespace OfficeWatermark
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //colorTextbox.Text = colorTextbox.BackColor.ToString();


            fileTypeRadios.Add(radioBtnWord);
            fileTypeRadios.Add(radioBtnExcel);
            fileTypeRadios.Add(radioBtnPPT);
            fileTypeRadios.Add(radioBtnPdf);

            waterMarkTypeRadios.Add(radioBtnImage);
            waterMarkTypeRadios.Add(radioBtnText);

            convertFileTypeRadios.Add(radioPdfToWord);
            convertFileTypeRadios.Add(radioWordToPDF);
            convertFileTypeRadios.Add(radioExcelToPDF);
            convertFileTypeRadios.Add(radioPdfToExcel);

            codeTypeRadios.Add(radioQRCode);
            codeTypeRadios.Add(radioBarCode);

            radioBtnText.Checked = true;
            panel2.Visible = false;
            panel1.Visible = true;
            radioBtnWord.Checked = true;
            filter = "word files (*.doc)|*.docx";
            AddWatermarkImpl = wordWatermark;
            waterMarkType = "text";

            ConvertFileType = WordToPdf;
        }



        private string waterMarkType = "text";

        private string sourceFilePath = "";

        private string sourceFileName = "";

        private string textWaterMark = "";

        private string fileType = "";

        private string filter = "";

        private string convertFilter = "";
        private bool isFrozen = false;

        private float opacity
        {
            get => (float)(Convert.ToInt32(this.trackBar1.Value.ToString()) * 1.0 / 100);
        }


        private Func<string> AddWatermarkImpl;

        private Action<string> ConvertFileType;
        List<RadioButton> fileTypeRadios = new List<RadioButton>();
        List<RadioButton> waterMarkTypeRadios = new List<RadioButton>();


        List<RadioButton> convertFileTypeRadios = new List<RadioButton>();

        List<RadioButton> codeTypeRadios = new List<RadioButton>();



        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = @"C:\Users\35024\Desktop";
            openFileDialog.Title = "选择要添加水印的文件";
            openFileDialog.Filter = filter;
            var dialogResult = openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string path = openFileDialog.FileName;
                textBox1.Text = path;
                sourceFilePath = path;
                sourceFileName = openFileDialog.SafeFileName;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Title = "选择水印图片",
                Filter = "图像文件(*.jpg;*.gif;*.png)|*.jpg;*.gif;*.png",
                InitialDirectory = @"D:\图片墙"
            };

            var dialogResult = openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string path = openFileDialog.FileName;
                pictureBox1.ImageLocation = path;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            try
            {

                if (waterMarkType == "text")
                {
                    if (string.IsNullOrWhiteSpace(textBox2.Text))
                    {
                        MessageBox.Show("请输入待添加的水印文字");
                        return;
                    }

                    textWaterMark = textBox2.Text;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(pictureBox1.ImageLocation))
                    {
                        MessageBox.Show("请输入待添加的水印图片");
                        return;
                    }
                }

                if (checkboxQRCode.Checked)
                {
                    if (!radioQRCode.Checked && !radioBarCode.Checked)
                    {
                        MessageBox.Show("请选择二维码类型");
                        return;
                    }
                    if (radioBarCode.Checked)
                    {
                        bool isNumber = false;
                        int parsedRes = 0;
                        foreach (char c in BarCodeText.Text)
                        {
                            isNumber = int.TryParse(c.ToString(), out parsedRes);
                            if (!isNumber)
                            {
                                MessageBox.Show("条形码只能输入数字");
                                return;
                            }
                        }

                    }
                }
                this.Cursor = Cursors.WaitCursor;
                btnConfirmAddWartermark.Text = "正在添加...";
                exeTime.Text = "";
                int totalSecends = 0;

                timer.Enabled = true;
                timer.Interval = 100;
                timer.Start();
                timer.Elapsed += (object timerSender, ElapsedEventArgs timerEvent) =>
                {
                    totalSecends += (int)timer.Interval;
                    Control.CheckForIllegalCrossThreadCalls = false;
                    exeTime.Text = (totalSecends * 1.0 / 1000).ToString();
                    //this.BeginInvoke((Action)(() =>
                    //{
                    //    exeTime.Text = (totalSecends * 1.0 / 1000).ToString();
                    //}));
                };

                Task.Run(() =>
                {
                    AddWatermark();
                }).Wait();

                timer.Stop();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace.ToString(), ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
                timer.Stop();
                timer.Enabled = false;
                this.Cursor = Cursors.Default;
                btnConfirmAddWartermark.Text = "添加水印";
            }




        }


        private void AddWatermark()
        {

            string savedName = AddWatermarkImpl();
            //保存文档


            Process process = new Process();
            process.StartInfo.FileName = savedName;
            process.Start();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }




        public string wordWatermark()
        {
            //新建一个word文档对象并加载需要添加水印的word文档
            Spire.Doc.Document document = new Spire.Doc.Document();
            document.LoadFromFile(sourceFilePath);

            if (cbxConvertToPdf.Checked)
            {
                ToPdfParameterList topdf = new ToPdfParameterList();
                topdf.CreateWordBookmarks = true;
                topdf.CreateWordBookmarksUsingHeadings = true;

                string saveFileName = sourceFileName;
                string fileName = sourceFilePath.Substring(0, sourceFilePath.LastIndexOf(".") - 1);
                string newPath = fileName + ".pdf";

                document.SaveToFile(newPath, topdf);

                //加载PDF文档
                PdfDocument pdf = new PdfDocument();
                pdf.LoadFromFile(newPath);

                Image image = GetCodeImage();
                var newImage = image;
                //var newImage = ImageProcessor.ZoomAuto(image, 120, 50);
                foreach (PdfPageBase page in pdf.Pages)
                {
                    if (checkboxQRCode.Checked)
                    {
                        //Image image = Image.FromFile(@"C:\Users\35024\Desktop\下载.png");

                        //调整图片大小
                        int width = newImage.Width;
                        int height = newImage.Height;

                        PdfImage pdfImage = PdfImage.FromImage(newImage);
                        page.Canvas.DrawImage(pdfImage, new PointF(0f, 0f));
                    }



                    //绘制文本，设置文本格式并将其添加到页面
                    PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 5, page.Canvas.ClientSize.Height / 5));
                    brush.Graphics.SetTransparency(0.3f);
                    brush.Graphics.Save();
                    brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                    brush.Graphics.RotateTransform(-45);
                    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 20f), true);
                    brush.Graphics.DrawString(textWaterMark, font, PdfBrushes.Red, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
                    brush.Graphics.Restore();
                    brush.Graphics.SetTransparency((float)0.5);
                    page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

                }

                pdf.SaveToFile(newPath);
                return newPath;
            }

            if (waterMarkType == "text")
            {
                //多行水印
                if (checkboxIsMutiple.Checked)
                {
                    //添加艺术字并设置大小
                    ShapeObject shape = new ShapeObject(document, Spire.Doc.Documents.ShapeType.TextPlainText);
                    shape.Width = 60;
                    shape.Height = 20;
                    //设置艺术字文本内容、位置及样式
                    shape.VerticalPosition = 30;
                    shape.HorizontalPosition = 20;
                    shape.LineStyle = ShapeLineStyle.Single;
                    ; shape.Rotation = 315;
                    shape.WordArt.Text = textWaterMark;
                    shape.FillColor = colorTextbox.BackColor;
                    shape.StrokeColor = System.Drawing.Color.Gray;
                    Section section;
                    HeaderFooter header;

                    Func<Section, Paragraph> getImageParagraph = (Section tempSection) =>
                    {
                        foreach (Paragraph paragraph in tempSection.Paragraphs)
                        {
                            //遍历段落中的每个DocumentObject
                            foreach (DocumentObject docObject in paragraph.ChildObjects)
                            {
                                //判断DocumentObject是否为图片
                                if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                                {
                                    return paragraph;
                                }
                            }

                        }
                        return null;
                    };
                    Image image = GetCodeImage();
                    //var newImage = image;
                    var newImage = ImageProcessor.ZoomAuto(image, 120, 120);


                    for (int n = 0; n < document.Sections.Count; n++)
                    {
                        section = document.Sections[n];

                        //获取section的页眉
                        header = section.HeadersFooters.Header;
                        List<ShapeObject> shapeObjects = new List<ShapeObject>();
                        Paragraph paragraph1 = header.AddParagraph();

                        if (checkboxQRCode.Checked)
                        {
                            //Image image = Image.FromFile(@"C:\Users\35024\Desktop\下载.png");


                            paragraph1.AppendText("北京xx集团-研发部   ");

                            var picture = paragraph1.AppendPicture(newImage);
                            //picture.HorizontalAlignment = ShapeHorizontalAlignment.Left;
                            //picture.HorizontalOrigin = HorizontalOrigin.LeftMarginArea;
                            //picture.VerticalAlignment = ShapeVerticalAlignment.Bottom;
                            //picture.VerticalOrigin = VerticalOrigin.BottomMarginArea;
                        }


                        paragraph1.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;
                        for (int i = 0; i < 9; i++)
                        {
                            //添加段落到页眉

                            for (int j = 0; j < 9; j++)
                            {
                                //复制艺术字并设置多行多列位置

                                shape = (ShapeObject)shape.Clone();
                                shape.VerticalPosition = 70 + 150 * i;
                                shape.HorizontalPosition = 20 + 160 * j;
                                //shape.WordArt.Text = $"{ shape.HorizontalPosition},{shape.VerticalPosition}";
                                shapeObjects.Add(shape);
                                paragraph1.ChildObjects.Add(shape);

                            }
                        }

                        //段落艺术字
                        //for (int i = 0; i < section.Paragraphs.Count; i++)
                        //{
                        //    Paragraph paragraph = section.Paragraphs[i];


                        //    for (int j = 0; j < paragraph.ChildObjects.Count; j++)
                        //    {
                        //        DocumentObject docObject = paragraph.ChildObjects[j];
                        //        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        //        {
                        //            var body = (Spire.Doc.Body)paragraph.Owner;

                        //            var firstP = (Paragraph)body.FirstParagraph;

                        //            shapeObjects.ForEach(shapObj =>
                        //            {
                        //                var textShape = firstP.AppendShape((float)shape.Width, (float)shape.Height,
                        //           Spire.Doc.Documents.ShapeType.TextPlainText);
                        //                textShape.Width = shape.Width;
                        //                textShape.Height = shape.Height;
                        //                //设置艺术字文本内容、位置及样式
                        //                //textShape.VerticalPosition = shape.VerticalPosition;
                        //                //textShape.HorizontalPosition = shape.HorizontalPosition;
                        //                textShape.Rotation = shape.Rotation;
                        //                textShape.WordArt.Text = shape.WordArt.Text;
                        //                textShape.FillColor = shape.FillColor;
                        //                textShape.StrokeColor = shape.StrokeColor;
                        //                textShape.VerticalPosition = shapObj.VerticalPosition - 50;
                        //                textShape.HorizontalPosition = shapObj.HorizontalPosition;


                        //                //textShape.WordArt.Text = $"{ textShape.HorizontalPosition},{textShape.VerticalPosition}";
                        //            });



                        //        }
                        //    }

                        //}

                    }
                }
                else
                {
                    //新建一个文本水印对象，并添加待设置为水印的文本
                    TextWatermark txtWatermark = new TextWatermark();
                    txtWatermark.Text = textWaterMark;

                    //设置文本的字体大小,颜色及文本的排列方式
                    txtWatermark.FontSize = 45;
                    txtWatermark.Color = colorTextbox.BackColor;
                    txtWatermark.Layout = WatermarkLayout.Diagonal;
                    document.Watermark = txtWatermark;
                }

            }
            else
            {
                //新建一个图片水印对象并添加为待设置水印的图片

                PictureWatermark picture = new PictureWatermark();
                picture.Picture = System.Drawing.Image.FromFile(pictureBox1.ImageLocation);

                //根据需要设置图片的大小，将其设置为文档的水印
                picture.Scaling = 100;
                document.Watermark = picture;
            }
            //document.Protect(ProtectionType.AllowOnlyReading, "123");

            foreach (Paragraph p in document.Sections[0].Body.Paragraphs)
            {
                var a = p.Format.PageBreakAfter;
                string content = p.Text;
                if (!string.IsNullOrEmpty(content))
                {
                    var b = 12;
                }
             
            }

            string savedName = $"{sourceFilePath}_watermarked.docx";
            document.SaveToFile(savedName);
            return savedName;





        }

        public string excelWatermark()
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sourceFilePath);
            if (cbxConvertToPdf.Checked)
            {

                //xls to pdf
                string saveFileName = sourceFileName;
                string fileName = sourceFilePath.Substring(0, sourceFilePath.LastIndexOf(".") - 1);
                string newPath = fileName + ".pdf";
                workbook.SaveToFile(newPath, Spire.Xls.FileFormat.PDF);

                //加载PDF文档
                PdfDocument pdf = new PdfDocument();
                pdf.LoadFromFile(newPath);
                Image image = GetCodeImage();
                var newImage = ImageProcessor.ZoomAuto(image, 50, 50);

                foreach (PdfPageBase page in pdf.Pages)
                {
                    if (checkboxQRCode.Checked)
                    {
                        //Image image = Image.FromFile(@"C:\Users\35024\Desktop\下载.png");


                        //调整图片大小
                        int width = newImage.Width;
                        int height = newImage.Height;
                        float scale = 0.8f;  //缩放比例
                        SizeF size = new SizeF(width * scale, height * scale);
                        //加载缩放后的图片到PdfImage对象
                        PdfImage pdfImage = PdfImage.FromImage(newImage);
                        page.Canvas.DrawImage(pdfImage, new PointF(0f, 0f));
                    }



                    //绘制文本，设置文本格式并将其添加到页面
                    PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 5, page.Canvas.ClientSize.Height / 5));
                    brush.Graphics.SetTransparency(0.3f);
                    brush.Graphics.Save();
                    brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                    brush.Graphics.RotateTransform(-45);
                    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 20f), true);
                    brush.Graphics.DrawString(textWaterMark, font, PdfBrushes.Red, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
                    brush.Graphics.Restore();
                    brush.Graphics.SetTransparency((float)0.5);
                    page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

                }

                pdf.SaveToFile(newPath);
                return newPath;
            }

            if (waterMarkType == "text")
            {
                //加载示例文档

                //设置文本和字体大小
                Font font = new System.Drawing.Font("仿宋", 40);
                String watermark = textWaterMark;
                List<string> tempImage = new List<string>();
                foreach (Worksheet sheet in workbook.Worksheets)
                {

                    System.Drawing.Image imgWtrmrk = null;
                    if (checkboxIsMutiple.Checked)
                    {
                        //imgWtrmrk = ImageProcessor
                        //    .DrawMutipleText(watermark, font, System.Drawing.Color.LightCoral,
                        //    System.Drawing.Color.White, sheet.PageSetup.PageHeight, sheet.PageSetup.PageWidth);

                        //将图片设置为页眉
                        //imgWtrmrk = ImageProcessor.DrawWords(watermark, colorTextbox.BackColor, opacity, (int)sheet.PageSetup.PageWidth, (int)sheet.PageSetup.PageHeight);

                        double width = 0.0;
                        double height = 0.0;

                        for (int j = 1; j <= sheet.LastColumn; j++)
                        {
                            width += sheet.Range[sheet.LastRow, j].ColumnWidth;
                        }

                        for (int i = 1; i <= sheet.LastRow; i++)
                        {
                            height += sheet.Range[i, sheet.LastColumn].RowHeight;
                        }

                        int sheetWidth = Math.Max((int)(width * 7.2), 2500);
                        int sheetHeight = Math.Max((int)(height * 1.5), 1600);

                        var defaultImage = ImageProcessor.DrawWords(textWaterMark, colorTextbox.BackColor,
                    opacity, sheetWidth, sheetHeight
                );
                        string rootDir = AppDomain.CurrentDomain.BaseDirectory + "File\\";
                        string dir = rootDir + DateTime.Now.ToString("yyyyMMdd");
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        string imgPath = dir + "\\" + Guid.NewGuid() + ".png";
                        tempImage.Add(imgPath);
                        defaultImage.Save(imgPath);
                        //var excelPicture = sheet.Pictures.Add(defaultImage,"水印背景");
                        var excelPicture = sheet.Pictures.Add(imgPath);

                        excelPicture.Top = 0;
                        excelPicture.Left = 0;

                        //sheet.Protect("123", SheetProtectionType.None);

                    }
                    else
                    {

                        imgWtrmrk = ImageProcessor
                         .DrawText(watermark, font, colorTextbox.BackColor,
                         System.Drawing.Color.White, sheet.PageSetup.PageHeight, sheet.PageSetup.PageWidth);
                        //将图片设置为页眉
                    }

                    //sheet.PageSetup.LeftHeaderImage = imgWtrmrk;
                    //Image image = GetCodeImage();
                    //var newImage = ImageProcessor.ZoomAuto(image, 40, 40);
                    //if (checkboxQRCode.Checked)
                    //{


                    //    sheet.PageSetup.CenterHeader = "&G";
                    //    sheet.PageSetup.CenterHeaderImage = newImage;
                    //}

                    //sheet.PageSetup.LeftHeader = "&G";
                    ////将显示模式设置为Layout
                    //sheet.ViewMode = ViewMode.Layout;
                }
            }
            else
            {
                foreach (Worksheet sheet in workbook.Worksheets)
                {

                    //var image = Image.FromFile(pictureBox1.ImageLocation);
                    //image = ImageProcessor.ZoomAuto(image, sheet.PageSetup.PageWidth, sheet.PageSetup.PageHeight);
                    //var excelPicture = sheet.Pictures.Add(image, "背景图片");
                    //sheet.PageSetup.PageHeight

                    var excelPicture = sheet.Pictures.Add(pictureBox1.ImageLocation);
                    double width = 0.0;
                    double height = 0.0;
                    for (int i = 1; i <= sheet.LastRow; i++)
                    {
                        for (int j = 1; j <= sheet.LastColumn; j++)
                        {
                            string text = sheet.Range[i, j].DisplayedText;
                            Color color = sheet.Range[i, j].Style.Color;
                            //string text = sheet.GetText(i,j);
                            if (!string.IsNullOrEmpty(text))
                            {
                                width += sheet.Range[i, j].ColumnWidth;
                                height += sheet.Range[i, j].RowHeight;
                            }
                        }
                    }
                    excelPicture.Top = 0;
                    excelPicture.Left = 0;
                    double percent = excelPicture.Width * 1.0 / excelPicture.Height;
                    excelPicture.Width = (int)Math.Max((double)excelPicture.Width, width * 7.2);
                    excelPicture.Height = (int)Math.Max((double)excelPicture.Height, (int)(excelPicture.Width / percent));
                    //excelPicture.Width = (int)(width * 7.2);
                    //excelPicture.Height = (int)(excelPicture.Width / percent);
                    //Bitmap bm = new Bitmap(Image.FromFile(pictureBox1.ImageLocation));
                    ////bm = ImageProcessor.SetImgAlpha(bm, 120);
                    //sheet.PageSetup.BackgoundImage = bm;
                    sheet.Protect("123", SheetProtectionType.None);
                }

            }
            //workbook.Protect();
            string savedName = $"{sourceFilePath}_watermarked.xlsx";
            //保存文档

            workbook.SaveToFile(savedName);
            return savedName;
        }


        public string pdfWatermark()
        {
            //加载PDF文档
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile(sourceFilePath);

            if (waterMarkType == "text")
            {
                Image image = GetCodeImage();

                var newImage = ImageProcessor.ZoomAuto(image, 50, 50);

                foreach (PdfPageBase page in pdf.Pages)
                {
                    if (checkboxQRCode.Checked)
                    {


                        //调整图片大小
                        int width = newImage.Width;
                        int height = newImage.Height;
                        float scale = 0.8f;  //缩放比例
                        SizeF size = new SizeF(width * scale, height * scale);
                        //加载缩放后的图片到PdfImage对象
                        PdfImage pdfImage = PdfImage.FromImage(newImage);
                        page.Canvas.DrawImage(pdfImage, new PointF(0f, 0f));
                    }



                    //绘制文本，设置文本格式并将其添加到页面
                    PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 5, page.Canvas.ClientSize.Height / 5));
                    brush.Graphics.SetTransparency(0.3f);
                    brush.Graphics.Save();
                    brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                    brush.Graphics.RotateTransform(-45);
                    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 20f), true);
                    brush.Graphics.DrawString(textWaterMark, font, PdfBrushes.Red, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
                    brush.Graphics.Restore();
                    brush.Graphics.SetTransparency((float)0.5);
                    page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

                }

            }
            else
            {
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //获取图片并将其设置为页面的背景图
                    Image img = System.Drawing.Image.FromFile(pictureBox1.ImageLocation);
                    //获取PDF文档的第一页

                    page.BackgroundImage = img;
                    //指定背景图的位置和大小
                    page.BackgroundRegion = page.BackgroundRegion;//全屏
                }

            }





            string savedName = $"{sourceFilePath}_watermarked.pdf";
            //保存文档
            pdf.SaveToFile(savedName);
            return savedName;

        }


        public string pptWatermark()
        {
            //加载PPT文档
            Presentation ppt = new Presentation();
            ppt.LoadFromFile(sourceFilePath, Spire.Presentation.FileFormat.Auto);
            var width = ppt.SlideSize.Size.Width;
            var height = ppt.SlideSize.Size.Height;
            float colWidth = width / 3;
            float rowHeight = height / 3;

            System.Diagnostics.Debug.WriteLine($"width:{width};height:{height}");

            System.Diagnostics.Debug.WriteLine($"colWidth:{colWidth};rowHeight:{rowHeight}");
            if (waterMarkType == "text")
            {

                //获取文本的大小
                Font stringFont = new Font("Arial", 25);
                Size size = TextRenderer.MeasureText(textBox2.Text, stringFont);



                //绘制文本，设置文本格式并将其添加到第二张幻灯片
                foreach (ISlide slide in ppt.Slides)
                {
                    //slide
                    for (int i = 1; i <= 3; i++)
                    {
                        for (int j = 1; j <= 3; j++)
                        {
                            RectangleF rect = new RectangleF(colWidth * (j - 1), (i - 1) * rowHeight, colWidth, rowHeight);
                            System.Diagnostics.Debug.WriteLine($"i:{i},j:{j} colWidth:{colWidth * (j - 1)};rowHeight:{ (i - 1) * rowHeight}");

                            IAutoShape shape = slide.Shapes.AppendShape(Spire.Presentation.ShapeType.Rectangle, rect);
                            shape.Fill.FillType = FillFormatType.None;
                            shape.ShapeStyle.LineColor.Color = Color.White;
                            //shape.Rotation = -45;
                            shape.Locking.SelectionProtection = true;
                            shape.Line.FillType = FillFormatType.None;
                            shape.TextFrame.Text = textBox2.Text;

                            shape.TextFrame.RotationAngle = -45;
                            Spire.Presentation.TextRange textRange = shape.TextFrame.TextRange;

                            textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
                            textRange.Fill.SolidColor.Color = Color.FromArgb(50, colorTextbox.BackColor);
                            textRange.FontHeight = 25;
                        }


                    }

                }


            }
            else
            {

                #region 设置图片背景
                ////为第一张幻灯片设置背景图片类型和样式
                //ppt.Slides[0].SlideBackground.Type = Spire.Presentation.Drawing.BackgroundType.Custom;
                //ppt.Slides[0].SlideBackground.Fill.FillType = FillFormatType.Picture;
                //ppt.Slides[0].SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch;
                ////获取图片并将其设置为页面的背景图
                //Image img = Image.FromFile(pictureBox1.ImageLocation);
                //IImageData bgImage = ppt.Images.Append(img);
                //ppt.Slides[0].SlideBackground.Fill.PictureFill.Picture.EmbedImage = bgImage;
                #endregion
                Image img = Image.FromFile(pictureBox1.ImageLocation);
                IImageData imageData = ppt.Images.Append(img);
                foreach (ISlide slide in ppt.Slides)
                {

                    RectangleF rect = new RectangleF(new PointF(0, 0), ppt.SlideSize.Size);
                    IEmbedImage embedImage = slide.Shapes.AppendEmbedImage(Spire.Presentation.ShapeType.Rectangle, imageData, rect);
                    embedImage.Line.FillType = FillFormatType.None;
                }

            }
            Image image = GetCodeImage();

            if (checkboxQRCode.Checked)
            {
                var newImage = ImageProcessor.ZoomAuto(image, 40, 40);
                //Image image = Image.FromFile(@"C:\Users\35024\Desktop\下载.png");

                ImageConverter imgconv = new ImageConverter();
                byte[] b = (byte[])imgconv.ConvertTo(newImage, typeof(byte[]));
                MemoryStream memoryStream = new MemoryStream(b);

                foreach (ISlide slide in ppt.Slides)
                {
                    RectangleF rect = new RectangleF(0, 0, 50, 50);
                    slide.Shapes.AppendEmbedImage(Spire.Presentation.ShapeType.Rectangle, memoryStream, rect);
                }
            }

            string savedName = $"{sourceFileName}_watermarked.pptx";
            //保存文档
            ppt.SaveToFile(savedName, Spire.Presentation.FileFormat.Auto);
            return savedName;

        }
        public void WaterMarkTypeRadioCheckedChanged(object sender)
        {
            if (isFrozen) return;
            isFrozen = true;
            var radio = (sender as RadioButton);
            waterMarkTypeRadios.ForEach(n => n.Checked = false);
            radio.Checked = true;

            if (radio.Text == "文字")
            {
                panel2.Visible = false;
                panel1.Visible = true;
                waterMarkType = "text";
            }
            else
            {
                panel1.Visible = false;
                panel2.Visible = true;
                waterMarkType = "image";

            }
            isFrozen = false;
        }

        public void FileTypeRadioCheckChanged(Object sender)
        {
            if (isFrozen) return;
            isFrozen = true;
            var radio = (sender as RadioButton);
            fileTypeRadios.ForEach(n => n.Checked = false);
            radio.Checked = true;
            fileType = radio.Text;

            if (radio.Text == "word")
            {
                filter = "word files (*.doc)|*.docx";
                AddWatermarkImpl = wordWatermark;
            }
            else if (radio.Text == "excel")
            {
                filter = "excel files (*.xls)|*.xlsx";
                AddWatermarkImpl = excelWatermark;
            }
            else if (radio.Text == "pdf")
            {
                filter = "pdf files (*.pdf)|*.pdf";
                AddWatermarkImpl = pdfWatermark;
            }
            else if (radio.Text == "ppt")
            {
                filter = "ppt files (*.ppt)|*.pptx";
                AddWatermarkImpl = pptWatermark;

            }
            isFrozen = false;
        }
        private void radioBtnPPT_Click(object sender, EventArgs e)
        {
            FileTypeRadioCheckChanged(sender);
        }

        private void radioBtnText_Click(object sender, EventArgs e)
        {
            WaterMarkTypeRadioCheckedChanged(sender);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            textWaterMark = textBox2.Text;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                var image = ImageProcessor.DrawWords(textWaterMark, colorTextbox.BackColor,
                    opacity, 2000, 1200
                );

                //var image =  ImageProcessor.CreateTransparentImage(1200,720);
                image.Save(foldPath + "/markBg.png");
                Process.Start(foldPath + "/markBg.png");
            }


        }



        private void button5_Click(object sender, EventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            colorDialog.Color = colorTextbox.BackColor;
            var dialogResult = colorDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                colorTextbox.Text = colorDialog.Color.ToArgb().ToString();
                colorTextbox.BackColor = colorDialog.Color;
            }
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            lblOpacity.Text = trackBar1.Value.ToString() + "%";
        }

        private void btnConvertChooseFile_Click(object sender, EventArgs e)
        {
            if (!convertFileTypeRadios.Any(n => n.Checked))
            {
                MessageBox.Show("请选择转换类型");
                return;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = @"C:\Users\35024\Desktop";
            openFileDialog.Title = "选择要转换文件";
            openFileDialog.Filter = convertFilter;
            var dialogResult = openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string path = openFileDialog.FileName;
                txtConvertFile.Text = path;
                txtConvertFile.Tag = openFileDialog.SafeFileName;
            }
        }





        private void WordToPdf(string savePath)
        {
            Document doc = new Document();
            doc.LoadFromFile(txtConvertFile.Text);
            ToPdfParameterList topdf = new ToPdfParameterList();
            topdf.CreateWordBookmarks = true;
            topdf.CreateWordBookmarksUsingHeadings = true;

            string saveFileName = txtConvertFile.Tag.ToString();
            string fileName = saveFileName.Substring(0, saveFileName.IndexOf(".") - 1);
            string newPath = savePath + "/" + fileName + ".pdf";

            doc.SaveToFile(newPath, topdf);

        }

        private void PdfToWord(string savePath)
        {
            //初始化PdfDocument实例
            PdfDocument doc = new PdfDocument();

            //加载PDF文档
            doc.LoadFromFile(txtConvertFile.Text);

            string saveFileName = txtConvertFile.Tag.ToString();

            string fileName = saveFileName.Substring(0, saveFileName.IndexOf("."));


            string newFilePath = savePath + "/" + fileName + ".docx";
            //保存为Doc格式文档
            doc.SaveToFile(newFilePath, Spire.Pdf.FileFormat.DOCX);


            Document wordDoc = new Document();
            wordDoc.LoadFromFile(newFilePath);
            wordDoc.Protect(ProtectionType.AllowOnlyReading, "123");
            wordDoc.SaveToFile(newFilePath);
        }


        private void ExcelToPdf(string savePath)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(txtConvertFile.Text);

            string saveFileName = txtConvertFile.Tag.ToString();
            string fileName = saveFileName.Substring(0, saveFileName.IndexOf(".") - 1);
            string newPath = savePath + "/" + fileName + ".pdf";

            workbook.SaveToFile(newPath, Spire.Xls.FileFormat.PDF);

        }

        private void PdfToExcel(string savePath)
        {
            //初始化PdfDocument实例
            PdfDocument doc = new PdfDocument();

            //加载PDF文档
            doc.LoadFromFile(txtConvertFile.Text);

            string saveFileName = txtConvertFile.Tag.ToString();

            string fileName = saveFileName.Substring(0, saveFileName.IndexOf(".") - 1);
            //保存为Doc格式文档
            doc.SaveToFile(savePath + "/" + fileName + ".xlsx", Spire.Pdf.FileFormat.XLSX);
        }

        private void btnConfirmConvert_Click(object sender, EventArgs e)
        {
            if (!convertFileTypeRadios.Any(n => n.Checked))
            {
                MessageBox.Show("请选择转换类型");
                return;
            }

            if (txtConvertFile.Text == "")
            {
                MessageBox.Show("请选择要转换的文件");
                return;
            }

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择保存文件的位置";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                try
                {

                    btnConfirmConvert.Text = "正在转换中...";
                    this.Cursor = Cursors.WaitCursor;

                    int totalSecends = 0;
                    System.Timers.Timer timer = new System.Timers.Timer();
                    timer.Enabled = true;
                    timer.Interval = 100;
                    timer.Start();
                    timer.Elapsed += (object timerSender, ElapsedEventArgs timerEvent) =>
                    {
                        totalSecends += (int)timer.Interval;
                        Control.CheckForIllegalCrossThreadCalls = false;
                        label8.Text = (totalSecends * 1.0 / 1000).ToString();
                    };
                    Task.Run(() =>
                    {
                        ConvertFileType(foldPath);
                    }).Wait();

                    timer.Stop();

                    if (IsAutoOpen.Checked)
                    {
                        System.Diagnostics.Process.Start("explorer.exe", foldPath);
                        //Process.Start(foldPath);
                    }
                    MessageBox.Show("转换完成");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.StackTrace, ex.Message);

                }
                finally
                {
                    this.Cursor = Cursors.Default;
                    btnConfirmConvert.Text = "开始转换";
                }

            }
        }

        private void radioPdfToWord_Click(object sender, EventArgs e)
        {
            var radio = (sender as RadioButton);
            convertFileTypeRadios.ForEach(n => n.Checked = false);
            radio.Checked = true;
            if (radio == radioWordToPDF)
            {
                convertFilter = "word files (*.doc)|*.docx";

                ConvertFileType = WordToPdf;
            }
            else if (radio == radioPdfToWord)
            {
                convertFilter = "pdf files (*.pdf)|*.pdf";

                ConvertFileType = PdfToWord;
            }
            else if (radio == radioExcelToPDF)
            {
                convertFilter = "excel files (*.xls)|*.xlsx";

                ConvertFileType = ExcelToPdf;
            }
            else if (radio == radioPdfToExcel)
            {
                convertFilter = "pdf files (*.pdf)|*.pdf";
                ConvertFileType = PdfToExcel;
            }
        }

        public Image QrCode(string text)
        {
            //创建BarcodeSettings对象
            BarcodeSettings settings = new BarcodeSettings();

            //设置条码类型为二维码
            settings.Type = BarCodeType.QRCode;

            //设置二维码数据
            settings.Data = text;
            settings.ShowText = false;

            //设置数据类型为数字
            settings.QRCodeDataMode = QRCodeDataMode.Auto;

            //设置二维码错误修正级别
            settings.QRCodeECL = QRCodeECL.H;

            //设置宽度
            settings.X = 2.0f;

            //初始化BarCodeGenerator对象
            BarCodeGenerator generator = new BarCodeGenerator(settings);

            //创建图片并保存为PNG格式
            Image image = generator.GenerateImage();
            return image;
        }

        public Image BarCode(string text)
        {
            BarcodeSettings settings = new BarcodeSettings();
            //设置条形码类型为DataMatrix
            settings.Type = BarCodeType.Codabar;
            settings.Data = text;
            settings.ShowText = false;
            //生成DataMatrix条形码并保存为png格式的图片
            BarCodeGenerator generator = new BarCodeGenerator(settings);
            Image image = generator.GenerateImage();
            return image;
        }

        private void checkboxQRCode_CheckedChanged(object sender, EventArgs e)
        {

            panelQRCode.Visible = (sender as CheckBox).Checked;

        }

        private void radioBarCode_Click(object sender, EventArgs e)
        {
            var radio = (sender as RadioButton);
            codeTypeRadios.ForEach(n => n.Checked = false);
            radio.Checked = true;
            if (radioQRCode.Checked)
            {
                this.QRCodeText.Visible = true;
                this.BarCodeText.Visible = false;
            }
            else
            {
                this.BarCodeText.Visible = true;
                this.QRCodeText.Visible = false;
            }
        }

        private Image GetCodeImage()
        {
            Image image = null;
            if (radioQRCode.Checked) image = QrCode(this.QRCodeText.Text);
            else if (radioBarCode.Checked) image = BarCode(this.BarCodeText.Text);
            return image;

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            FormQRCode formQRCode = new FormQRCode(this.QRCodeText.Text);
            formQRCode.ShowDialog();
        }

        private void btnChooseImageRotate_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Title = "选择图片",
                Filter = "图像文件(*.jpg;*.gif;*.png)|*.jpg;*.gif;*.png",
                InitialDirectory = @"D:\图片墙"
            };

            var dialogResult = openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string path = openFileDialog.FileName;
                pictureBoxOld.ImageLocation = path;
            }
        }

        private void btnRotate_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                var img = ImageProcessor.RotateImg(pictureBoxOld.Image, (float)numRotateAngle.Value);


                //var image =  ImageProcessor.CreateTransparentImage(1200,720);
                var fileName = foldPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
                img.Save(fileName);
                Process.Start(fileName);
                pictureBoxNew.Image = img;
            }


        }

        private void button6_Click(object sender, EventArgs e)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(sourceFilePath);
  
            string savedName = $"{sourceFilePath}_watermarked.xlsx";
            //保存文档
            workbook.SaveToFile(savedName);
         
        }
    }
}

